//
//  GGTSearchViewController.m
//  GGT
//
//  Created by 安静的美男子 on 14/10/27.
//  Copyright (c) 2014年 GGT. All rights reserved.
//

#import "GGTSearchViewController.h"
#import "GGTSearchResultViewController.h"
#import "DPRequest.h"
#import "GGTAppDelegate.h"
#import "GGTTeamBuyKindModel.h"
#import "DBSphereView.h"
#import "GGTSearchResultViewController.h"

@interface GGTSearchViewController ()<DPRequestDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>
@property (nonatomic, retain) NSMutableArray *GGTTeamBuyKindArr;
@property (nonatomic, retain) NSMutableArray *GGTTeamBuyBigKindArr;
@property (nonatomic, retain) DBSphereView *sphereView;
//搜索栏
@property (nonatomic, retain) UISearchBar *mySearchBar;
//配套uiSearchDisplayController
@property (nonatomic, retain) UISearchDisplayController *mySearchDisplayController;
//搜索数据
@property (nonatomic, retain) NSArray *searchData;
//搜索状态
@property (nonatomic, assign) BOOL isSearch;

@end

@implementation GGTSearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.GGTTeamBuyKindArr = [NSMutableArray array];
        self.GGTTeamBuyBigKindArr = [NSMutableArray array];
        self.searchData = [NSArray array];
        self.isSearch = NO;
    }
    return self;
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    NSArray *vcArray = self.tabBarController.viewControllers;
//    for (UIViewController *vc in vcArray) {
//        if ([vc isKindOfClass:[UINavigationController class]]) {
//            [vc.navigationController popToRootViewControllerAnimated:YES];
//        }
//    }
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *url = @"v1/metadata/get_categories_with_deals";
    [[[GGTAppDelegate instance] dpapi] requestWithURL:url paramsString:nil delegate:self];
    
    //搜索栏
    //searchBar
    
    self.mySearchBar = [[UISearchBar alloc] init];
    self.mySearchBar.frame =CGRectMake(0,0, self.view.frame.size.width ,44);
    self.mySearchBar.delegate = self;
    self.mySearchBar.placeholder =@"搜索";
    
    //SearchDisplayController
    
    
    self.mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.mySearchBar contentsController:self];
    self.searchDisplayController.delegate =self;
    self.mySearchDisplayController.searchResultsTableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.mySearchDisplayController.searchResultsDataSource =self;
    self.mySearchDisplayController.searchResultsDelegate =self;
    [self.mySearchDisplayController.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cityTableView"];
    self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
    
}


- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    NSMutableDictionary *kindDic =[result objectForKey:@"categories"];
    for (NSMutableDictionary * temp in kindDic) {
        GGTTeamBuyKindModel *kindModel = [[GGTTeamBuyKindModel alloc]initWithDictionary:temp];
        [self.GGTTeamBuyKindArr addObject:kindModel];
        [kindModel release];
    }
    for (GGTTeamBuyKindModel * temp in self.GGTTeamBuyKindArr) {
        [self.GGTTeamBuyBigKindArr addObject: temp.category_name];
        if (temp.subcategories.count == 0) {
            NSString *tempStr = [NSString stringWithFormat:@"%@",temp.category_name];
            [self.GGTTeamBuyBigKindArr addObject:tempStr];
        } else {
            for (NSString * tempStr in temp.subcategories) {
                [self.GGTTeamBuyBigKindArr addObject:tempStr];
            }
        }
    }

//创建标签云
    self.sphereView = [[DBSphereView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];

    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i < 40; i++) {
        
        UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [tempButton setTitle:[NSString stringWithFormat:@"%@", self.GGTTeamBuyBigKindArr[arc4random() % self.GGTTeamBuyBigKindArr.count]] forState:UIControlStateNormal];
        [tempButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        tempButton.titleLabel.font = [UIFont systemFontOfSize:20.];
        tempButton.frame = CGRectMake(0, 0, 140, 20);
        [tempButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [array addObject:tempButton];
        [self.sphereView addSubview:tempButton];
        
    }
    

    [self.sphereView setCloudTags:array];
    self.sphereView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.sphereView];
}
- (void)buttonClicked:(UIButton *)button
{
    [self.sphereView timerStop];
    
    [UIView animateWithDuration:0.3 animations:^{
        button.transform = CGAffineTransformMakeScale(2., 2.);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            button.transform = CGAffineTransformMakeScale(1., 1.);
        } completion:^(BOOL finished) {
            [self.sphereView timerStart];
        }];
    GGTSearchResultViewController *searchResultVC = [[GGTSearchResultViewController alloc]init];
        searchResultVC.keyword = button.titleLabel.text;
        [self.navigationController pushViewController:searchResultVC animated:YES];
        [searchResultVC release];
    }];

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    
    return 25;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

        return self.searchData.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityTableView"];
    

    // 使用searchData作为表格显示的数据
    cell.textLabel.text = [self.searchData objectAtIndex:indexPath.row];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    GGTSearchResultViewController *resuleVC = [[GGTSearchResultViewController alloc]init];
    resuleVC.keyword = cell.textLabel.text;
    [self.navigationController pushViewController:resuleVC animated:YES];
    [resuleVC release];

    //
    
    
}

// UISearchBarDelegate定义的方法，当搜索文本框内文本改变时激发该方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	// 调用filterBySubstring:方法执行搜索
	[self filterBySubstring:searchText];
}
// UISearchBarDelegate定义的方法，用户单击虚拟键盘上Search按键时激发该方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	// 调用filterBySubstring:方法执行搜索
	[self filterBySubstring:searchBar.text];
    GGTSearchResultViewController *searchVC = [[GGTSearchResultViewController alloc]init];
    searchVC.keyword = searchBar.text;
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
	// 放弃作为第一个响应者，关闭键盘
	[searchBar resignFirstResponder];
}
- (void) filterBySubstring:(NSString*) subStr
{
    
	self.isSearch = YES;
	NSPredicate* pred = [NSPredicate predicateWithFormat:
                         @"SELF CONTAINS[c] %@" , subStr];
	self.searchData = [self.GGTTeamBuyBigKindArr filteredArrayUsingPredicate:pred];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
